package com.bz.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

@Slf4j
public class Base64Utils {
    /**
     * base64转inputStream
     * 
     * @param base64string
     * @return
     */
    public static InputStream BaseToInputStream(String base64string) {
        ByteArrayInputStream stream = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64string);
            stream = new ByteArrayInputStream(bytes1);
        } catch (Exception e) {

            LogUtils.error(log, e, "图片转换失败");
            return null;
        }
        return stream;
    }

    /**
     * 获取文件base64编码
     *
     * @param path
     *            文件路径
     * @param urlEncode
     *            如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException
     *             IO异常
     */
    public static String getFileContentAsBase64(String path) {

        try {
            // new一个URL对象
            URL url = new URL(path);
            // 打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式为"GET"
            conn.setRequestMethod("GET");
            // 超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            // 得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] imgData = readInputStream(inStream);

            String imgStr = encode(imgData);
            return imgStr;
        } catch (Exception e) {
            LogUtils.error(log, e, "图片转base64失败!url:" + path);
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    private static final char   last2byte   = (char) Integer.parseInt("00000011", 2);
    private static final char   last4byte   = (char) Integer.parseInt("00001111", 2);
    private static final char   last6byte   = (char) Integer.parseInt("00111111", 2);
    private static final char   lead6byte   = (char) Integer.parseInt("11111100", 2);
    private static final char   lead4byte   = (char) Integer.parseInt("11110000", 2);
    private static final char   lead2byte   = (char) Integer.parseInt("11000000", 2);
    private static final char[] encodeTable = new char[] { 'A',
                                                           'B',
                                                           'C',
                                                           'D',
                                                           'E',
                                                           'F',
                                                           'G',
                                                           'H',
                                                           'I',
                                                           'J',
                                                           'K',
                                                           'L',
                                                           'M',
                                                           'N',
                                                           'O',
                                                           'P',
                                                           'Q',
                                                           'R',
                                                           'S',
                                                           'T',
                                                           'U',
                                                           'V',
                                                           'W',
                                                           'X',
                                                           'Y',
                                                           'Z',
                                                           'a',
                                                           'b',
                                                           'c',
                                                           'd',
                                                           'e',
                                                           'f',
                                                           'g',
                                                           'h',
                                                           'i',
                                                           'j',
                                                           'k',
                                                           'l',
                                                           'm',
                                                           'n',
                                                           'o',
                                                           'p',
                                                           'q',
                                                           'r',
                                                           's',
                                                           't',
                                                           'u',
                                                           'v',
                                                           'w',
                                                           'x',
                                                           'y',
                                                           'z',
                                                           '0',
                                                           '1',
                                                           '2',
                                                           '3',
                                                           '4',
                                                           '5',
                                                           '6',
                                                           '7',
                                                           '8',
                                                           '9',
                                                           '+',
                                                           '/' };

    public static String encode(byte[] from) {
        StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
        int num = 0;
        char currentByte = 0;

        int i;
        for (i = 0; i < from.length; ++i) {
            for (num %= 8; num < 8; num += 6) {
                switch (num) {
                    case 0:
                        currentByte = (char) (from[i] & lead6byte);
                        currentByte = (char) (currentByte >>> 2);
                    case 1:
                    case 3:
                    case 5:
                    default:
                        break;
                    case 2:
                        currentByte = (char) (from[i] & last6byte);
                        break;
                    case 4:
                        currentByte = (char) (from[i] & last4byte);
                        currentByte = (char) (currentByte << 2);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
                        }
                        break;
                    case 6:
                        currentByte = (char) (from[i] & last2byte);
                        currentByte = (char) (currentByte << 4);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
                        }
                }

                to.append(encodeTable[currentByte]);
            }
        }

        if (to.length() % 4 != 0) {
            for (i = 4 - to.length() % 4; i > 0; --i) {
                to.append("=");
            }
        }

        return to.toString();
    }

}
